package com.metaera.app.controller.presenter;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.metaera.app.MetaEraApplication;
import com.metaera.app.controller.core.RequestPresenter;
import com.metaera.app.controller.view.core.INetworkRequestView;

import java.util.ArrayList;
import java.util.List;

public class SearchHistoryPresenter extends RequestPresenter<INetworkRequestView<List<String>>> {

    private  List<String> mSearchHistoryList;

    private final String KEY = "SEARCH_HISTORY";
    private final SharedPreferences searchHistory;

    public SearchHistoryPresenter() {
        mSearchHistoryList = new ArrayList<>();

        searchHistory = MetaEraApplication.sInstance
                .getSharedPreferences("search_history", Context.MODE_PRIVATE);
    }

    public void find(){
        String string = searchHistory.getString(KEY, null);
        if (string != null){
            mSearchHistoryList = new Gson().fromJson(string, new TypeToken<List<String>>(){}.getType());
            mView.successful(mSearchHistoryList);
        }
    }

    public void add(CharSequence item) {
        if (item == null || item.length() <= 0) {
            return;
        }

        item = item.toString().trim();

        for (String historySearch : mSearchHistoryList) {
            if (item.equals(historySearch)) {
                return;
            }
        }

        mSearchHistoryList.add(item.toString());
        mView.successful(mSearchHistoryList);
        searchHistory.edit().putString(KEY, new Gson().toJson(mSearchHistoryList)).apply();
    }

    public void remove(String item) {
        for (int index = 0; index < mSearchHistoryList.size(); index++) {
            if (item.equals(mSearchHistoryList.get(index))) {
                mSearchHistoryList.remove(index);
                break;
            }
        }

        mView.successful(mSearchHistoryList);
        searchHistory.edit().putString(KEY, new Gson().toJson(mSearchHistoryList)).apply();
    }

    public void clear() {
        mSearchHistoryList.clear();
        mView.successful(mSearchHistoryList);
        searchHistory.edit().remove(KEY).apply();
    }

}
